//
//  OCOperatServiceManager.m
//  CaculatorTest
//
//  Created by rain on 2018/4/23.
//  Copyright © 2018年 rain. All rights reserved.
//

#import "OCOperatServiceManager.h"
#import "OCOPeratorProtocol.h"

@interface OCOperatServiceManager()
@property (nonatomic, strong) NSMutableDictionary *serviceClassDictionary;
@property (nonatomic, strong) NSMutableDictionary *serviceInstanceDictionary;
@end

@implementation OCOperatServiceManager
#pragma mark - Public Methods
- (instancetype)init
{
    if (self = [super init]) {
        _serviceClassDictionary = [NSMutableDictionary dictionary];
        _serviceInstanceDictionary = [NSMutableDictionary dictionary];
    }
    return self;
}

+ (instancetype)sharedManager
{
    static dispatch_once_t predicate;
    static id instance = nil;
    dispatch_once(&predicate, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (void)registerOperService:(Protocol *)protocol impClass:(Class)serviceClass
{
    NSString *protocolString = NSStringFromProtocol(protocol);
    NSString *serviceClassString = NSStringFromClass(serviceClass);
    
    if (![serviceClass conformsToProtocol:protocol]) {
        NSLog(@"服务注册失败！该类(%@)未实现服务协议(%@)!", serviceClassString, protocolString);
        return;
    }
    
    if (![protocolString isKindOfClass:[NSString class]] || ![serviceClassString isKindOfClass:[NSString class]]) {
        NSLog(@"服务注册失败！该类(%@)为空或服务协议为空(%@)!",serviceClassString, protocolString);
        return;
    }
    
    [self.serviceClassDictionary setObject:serviceClassString forKey:protocolString];
}

- (id)createOperService:(Protocol *)protocol
{
    if (protocol == nil) {
        NSLog(@"服务实现对象创建失败！服务协议不能为空!");
        return nil;
    }
    
    NSString *protocolString = NSStringFromProtocol(protocol);
    
    if (![protocolString isKindOfClass:[NSString class]]) {
        NSLog(@"服务实现对象创建失败！服务协议为空(%@)!", protocolString);
        return nil;
    }
    
    NSString *serviceClassString = self.serviceClassDictionary[protocolString];
    
    if (![serviceClassString isKindOfClass:[NSString class]]) {
        NSLog(@"服务实现对象创建失败！服务协议的实现对象类为空(%@)!", serviceClassString);
        return nil;
    }
    
    id implInstance = nil;
    Class serviceClass = NSClassFromString(serviceClassString);
    
    implInstance = [[serviceClass class] sharedInstance];
    id instance = self.serviceInstanceDictionary[protocolString];
    
    if (instance) {
        return instance;
    }
    else {
        [self.serviceInstanceDictionary setObject:implInstance forKey:protocolString];
    }
    return implInstance;
}

@end
